package com.dayanxs.Service;

import com.dayanxs.Utils.AESCryptoUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;

@Service
public class NovelChapterService {

    private final JdbcTemplate jdbcTemplate;
    private final SimpleDateFormat dateFormatter;

    public NovelChapterService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 指定时间格式
    }

    public ResponseEntity<?> getChaptersByNovelId(int chapterNovelID) {
        try {
            // 查询章节列表
            String sql = "SELECT id, chapter_title, update_time FROM novel_chapter WHERE chapter_novelID = ? ORDER BY update_time";
            List<Map<String, Object>> chapters = jdbcTemplate.queryForList(sql, new Object[]{chapterNovelID});
            // 优化时间格式
            for (Map<String, Object> chapter : chapters) {
                Object updateTime = chapter.get("update_time");
                if (updateTime instanceof Date) {
                    chapter.put("update_time", dateFormatter.format((Date) updateTime)); // 格式化时间
                }
            }

            return ResponseEntity.ok(chapters);

        } catch (Exception e) {
            return buildErrorResponse("Error retrieving chapters: " + e.getMessage(), 201);
        }
    }

    public ResponseEntity<?> getChapterById(int chapterId) {
        try {
            // 查询当前章节信息
            String chapterSql = "SELECT * FROM novel_chapter WHERE id = ?";
            Map<String, Object> chapter = jdbcTemplate.queryForMap(chapterSql, new Object[]{chapterId});

            if (chapter == null) {
                return buildErrorResponse("章节没有找到！", 201);
            }

            // 格式化 update_time
            Object updateTime = chapter.get("update_time");
            if (updateTime instanceof Date) {
                chapter.put("update_time", dateFormatter.format((Date) updateTime));
            }

            // 统计字符数
            String content = (String) chapter.get("chapter_content");
            int wordCount = content != null ? content.length() : 0;
            chapter.put("word_count", wordCount); // 添加字符计数

            // 获取小说和作者信息
            Integer chapterNovelID = (Integer) chapter.get("chapter_novelID");

            // 获取小说信息
            String novelSql = "SELECT * FROM novel WHERE novel_id = ?";
            Map<String, Object> novel = jdbcTemplate.queryForMap(novelSql, new Object[]{chapterNovelID});

            if (novel != null) {
                // 获取作者信息
                Integer novelAuthorID = (Integer) novel.get("novel_authorID");
                String authorSql = "SELECT nickname, introduce FROM user WHERE id = ?";
                Map<String, Object> author = jdbcTemplate.queryForMap(authorSql, new Object[]{novelAuthorID});

                if (author != null) {
                    novel.put("author", author); // 添加作者信息
                }

                chapter.put("novelInfo", novel); // 添加小说详细信息
            }

            chapter.remove("chapter_novelID"); // 移除原始的章节小说ID

            // 获取上一章和下一章
            Integer prevChapterId = null;
            Integer nextChapterId = null;

            // 获取上一章
            String prevChapterSql = "SELECT id FROM novel_chapter WHERE id < ? AND chapter_novelID = ? ORDER BY id DESC LIMIT 1";
            try {
                prevChapterId = jdbcTemplate.queryForObject(prevChapterSql, new Object[]{chapterId, chapterNovelID}, Integer.class);
            } catch (Exception e) {
                // 如果没有找到上一章，保持为空
                prevChapterId = null;
            }

            // 获取下一章
            String nextChapterSql = "SELECT id FROM novel_chapter WHERE id > ? AND chapter_novelID = ? ORDER BY id ASC LIMIT 1";
            try {
                nextChapterId = jdbcTemplate.queryForObject(nextChapterSql, new Object[]{chapterId, chapterNovelID}, Integer.class);
            } catch (Exception e) {
                // 如果没有找到下一章，保持为空
                nextChapterId = null;
            }

            chapter.put("prev_chapter_id", prevChapterId); // 添加上一章 ID
            chapter.put("next_chapter_id", nextChapterId); // 添加下一章 ID

            return ResponseEntity.ok(chapter); // 返回章节详情

        } catch (Exception e) {
            return buildErrorResponse("Error retrieving chapter: " + e.getMessage(), 201);
        }
    }


    public ResponseEntity<?> deleteChapter(int chapterId, String authorization) {
        try {
            // 检查 Authorization 头部
            String userToken = getToken(authorization); // 去掉 "Bearer " 前缀

            // 使用 AES 解密 cookie
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\.");
            if (parts.length != 2) {
                return buildErrorResponse("Invalid token format", 201);
            }

            String username = parts[0];

            String sql = "SELECT chapter_novelID FROM novel_chapter WHERE id = ?";
            Integer chapterNovelID = jdbcTemplate.queryForObject(sql, new Object[]{chapterId}, Integer.class);

            // 查询章节的作者 ID
            if (!isAdmin(username)) {
                sql = "SELECT id FROM user WHERE username = ?";
                Integer authorID = jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);

                sql = "SELECT novel_authorID FROM novel WHERE novel_id = ?";
                Integer novelAuthorID = jdbcTemplate.queryForObject(sql, new Object[]{chapterNovelID}, Integer.class);

                if (!Objects.equals(authorID, novelAuthorID)) {
                    return buildErrorResponse("你不是该章节的作者！", 201);
                }
            }

            // 删除章节
            sql = "DELETE FROM novel_chapter WHERE id = ?";
            jdbcTemplate.update(sql, chapterId);

            return buildSuccessResponse("章节删除成功！");

        } catch (Exception e) {
            return buildErrorResponse("Error deleting chapter: " + e.getMessage(), 201);
        }
    }

    public ResponseEntity<?> addChapter(String authorization, Map<String, String> chapterDetails) {
        try {
            // 检查 Authorization 头部

            String userToken = getToken(authorization); // 去掉 "Bearer " 前缀
            // 使用 AES 解密 userToken
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\.");
            if (parts.length != 2) {
                return buildErrorResponse("Invalid token format", 201);
            }

            String username = parts[0];

            // 查询作者 ID
            String sql = null;
            Integer chapterNovelID = Integer.parseInt(chapterDetails.get("chapter_novelID"));
            if (!isAdmin(username)) {
                sql = "SELECT id FROM user WHERE username = ?";
                Integer authorID = jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);


                sql = "SELECT novel_authorID FROM novel WHERE novel_id = ?";
                Integer novelAuthorID = jdbcTemplate.queryForObject(sql, new Object[]{chapterNovelID}, Integer.class);

                if (!Objects.equals(authorID, novelAuthorID)) {
                    return buildErrorResponse("你不是这本小说的作者！", 201);
                }
            }

            // 获取当前时间
            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            // 插入新章节
            sql = "INSERT INTO novel_chapter (chapter_title, chapter_content, update_time, chapter_novelID) VALUES (?, ?, ?, ?)";
            jdbcTemplate.update(sql, chapterDetails.get("chapter_title"), chapterDetails.get("chapter_content"), currentTime, chapterNovelID);

            return buildSuccessResponse("章节发布成功！");

        } catch (Exception e) {
            return buildErrorResponse("Error adding chapter: " + e.getMessage(), 201);
        }
    }

    public ResponseEntity<?> updateChapter(String authorization, Map<String, String> chapterDetails) {
        try {

            // 从 Authorization 中提取 Bearer 令牌
            String userToken = getToken(authorization); // 去掉 "Bearer " 前缀
            // 使用 AES 解密 userToken
            String decryptedData = AESCryptoUtil.decrypt(userToken);
            String[] parts = decryptedData.split("\\.");
            if (parts.length != 2) {
                return buildErrorResponse("Invalid token format", 201);
            }

            String username = parts[0];
            String chapterId = chapterDetails.get("chapterId");
            // 查询作者 ID
            String sql = null;
            if (!isAdmin(username)) {
                sql = "SELECT id FROM user WHERE username = ?";
                Integer authorID = jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);

                sql = "SELECT chapter_novelID FROM novel_chapter WHERE id = ?";
                Integer chapterNovelID = jdbcTemplate.queryForObject(sql, new Object[]{chapterId}, Integer.class);

                sql = "SELECT novel_authorID FROM novel WHERE novel_id = ?";
                Integer novelAuthorID = jdbcTemplate.queryForObject(sql, new Object[]{chapterNovelID}, Integer.class);

                if (!Objects.equals(authorID, novelAuthorID)) {
                    return buildErrorResponse("你不是这本书的作者！", 201);
                }
            }

            // 更新章节
            String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            sql = "UPDATE novel_chapter SET chapter_title = ?, chapter_content = ? WHERE id = ?";
            jdbcTemplate.update(sql, chapterDetails.get("chapter_title"), chapterDetails.get("chapter_content"), chapterId);

            return buildSuccessResponse("章节更新成功！");

        } catch (Exception e) {
            return buildErrorResponse("Error updating chapter: " + e.getMessage(), 201);
        }
    }

    private String getToken(String authorization) {
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return "";
        }
        // 从 Authorization 中提取 Bearer 令牌
        return authorization.substring(7);
    }

    public boolean isAdmin(String username) {
        try {
            // 查询用户是否是管理员
            String sql = "SELECT 1 FROM admin WHERE username = ?";
            jdbcTemplate.queryForObject(sql, new Object[]{username}, Integer.class);
            // 如果查询成功执行到这里，说明用户是管理员
            return true;
        } catch (EmptyResultDataAccessException e) {
            // 用户不存在于admin表中，返回false
            return false;
        } catch (Exception e) {
            // 处理其他可能的异常，例如数据库连接问题等
            // 这里可能需要记录日志或抛出更具体的异常
            // 但在当前的上下文中，我们简单地返回false
            return false;
        }
    }

    private ResponseEntity<Map<String, String>> buildErrorResponse(String message, int status) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("message", message);
        return ResponseEntity.status(status).body(errorResponse);
    }

    private ResponseEntity<Map<String, String>> buildSuccessResponse(String message) {
        Map<String, String> successResponse = new HashMap<>();
        successResponse.put("message", message);
        return ResponseEntity.ok(successResponse);
    }
    private int countChineseCharacters(String text) {
        if (text == null) {
            return 0;
        }
        // 使用正则表达式统计中文字符数
        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5a-zA-Z0-9]");
        Matcher matcher = pattern.matcher(text);
        int count = 0;
        while (matcher.find()) { // 查找所有匹配的字符
            count += matcher.group().length(); // 累加匹配的字符数
        }
        return count;
    }
}
